//
//  VideoPlayingViewController.m
//  NewVideo
//
//  Created by Jhero on 15/11/8.
//  Copyright © 2015年 Jhero. All rights reserved.
//

#import "VideoPlayingViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "NewCommentsTableViewCell.h"
#import "CommentTableViewCell.h"
#import "VideoWindowTableViewCell.h"
#import "NetManager.h"
#import "Tools.h"
#import "ConfigData.h"
//#import "UMSocial.h"
#import "NetManager.h"
#import "THud.h"
#import "UIImageView+WebCache.h"
#import "ShareMethods.h"
#import "Toast+UIView.h"
#import "LoginViewController.h"
#import "UIButton+WebCache.h"

#define TABLEVIEW_IDENTIF_VIDEO @"videocellIdentif"
#define TABLEVIEW_IDENTIF_COMMENT @"commentcellIdentif"
#define TABLEVIEW_IDENTIF_NEWCOMMENT @"newcommentIdentif"
#define SCREEN_SCALE_WIDTH [UIScreen mainScreen].bounds.size.width/320

@interface VideoPlayingViewController ()<UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UIView *inputView1;
@property (strong, nonatomic) IBOutlet UITextField *textField;
@property (strong, nonatomic) IBOutlet UITextField *inputTextField;
@property (strong, nonatomic) IBOutlet UIButton *atBtn;
@property (strong, nonatomic) IBOutlet UIButton *inputAtBtn;
@property (strong, nonatomic) IBOutlet UIView *inputView;
@property (strong, nonatomic) IBOutlet UILabel *customLabel;
@property (strong, nonatomic) UIView * backView;
@property (nonatomic, strong) NSArray *commentArray;
@end

@implementation VideoPlayingViewController
- (IBAction)sendComment:(id)sender {
    [self.view endEditing:YES];
    
    if (_commentTF.text.length == 0) {
        [[THud sharedInstance]showText:@"请输入评论"];
        return;
    }
    
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString *str = [ud objectForKey:@"uid"];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:@{
                                                                                @"uid":str,
                                                                                @"video_id":self.videoID,
                                                                                @"content":_commentTF.text
                                                                                }];
    [NetManager POST1DataWithParams:dic withUrl:@"/index.php/AppVideoComment/saveVideoComment" header:nil success:^(id object) {
        NSLog(@"---%@",object);
        //_commentArray = [NSMutableDictionary dictionaryWithDictionary:object];
        _commentArray = [object objectForKey:@"list"];
        [self loadData];
    } withAnimation:NO];
}

- (IBAction)cancelShareView:(id)sender {
    __block UIView * bb = _shareView;
    [UIView animateWithDuration:0.3 animations:^{
        bb.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width, 100);
    }];
    [_backView removeFromSuperview];
}
- (IBAction)doShareVideo:(id)sender {
//    NSArray *UMShareArray = [[NSArray alloc] initWithObjects:UMShareToWechatTimeline,UMShareToWechatSession,UMShareToQQ,UMShareToSina, nil];
//    UIButton *idShareBtn = (UIButton *)sender;
//    
//    [UMSocialAccountManager isOauthAndTokenNotExpired:UMShareArray[idShareBtn.tag - 10]];
//    
//    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareArray[idShareBtn.tag - 10]] content:@"分享内嵌文字" image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
//        if (response.responseCode == UMSResponseCodeSuccess) {
//            NSLog(@"分享成功！");
//        }
//    }];
    UIButton *btn = sender;
    if (btn.tag == 10) {
        [[ShareMethods shareInstance]shareLinkToWXTimeLine];
    }else if (btn.tag == 11) {
        [[ShareMethods shareInstance]shareLinkToWX];
    }else if (btn.tag == 12) {
        [[ShareMethods shareInstance]shareNews];
    }else if (btn.tag == 13) {
        [[ShareMethods shareInstance]shareLinkToWeibo];
    }
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataSource = [NSMutableDictionary dictionary];
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setObject:self.videoID forKey:@"videoId"];
    [NetManager POST1DataWithParams:dic withUrl:@"/index.php/appVideo/detailFn" header:nil success:^(id object) {
        NSLog(@"---%@",object);
        _dataSource = [NSMutableDictionary dictionaryWithDictionary:object];
        [self loadComment];
        //[self.commentTableView reloadData];
    } withAnimation:NO];
    self.textField.inputAccessoryView = self.inputView;
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back2016"]
                       forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backToPreView)
      forControlEvents:UIControlEventTouchUpInside];
    leftBtn.frame = CGRectMake(0, 0, 20, 20);
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    
//    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [rightBtn setBackgroundImage:[UIImage imageNamed:@"toolbar_user_icon"]
//                        forState:UIControlStateNormal];
////    [rightBtn addTarget:self action:@selector(messageHandler)
////       forControlEvents:UIControlEventTouchUpInside];
//    rightBtn.frame = CGRectMake(0, 0, 20, 20);
    
    //self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    [rightBtn setTitle:@"关注" forState:UIControlStateNormal];
    UIBarButtonItem *btnBar = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    [rightBtn addTarget:self action:@selector(editFn:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = btnBar;
    
    self.navigationItem.title = @"视频播放";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.commentTableView.tableHeaderView = nil;
    
    _inputView1.layer.borderWidth = 0.5;
    _inputView1.layer.borderColor = [[UIColor grayColor] CGColor];
    _customLabel.layer.borderWidth = 0.5;
    _customLabel.layer.borderColor = [[UIColor grayColor] CGColor];
    
//    _inputAtBtn.layer.borderWidth = 0.5;
//    _inputAtBtn.layer.borderColor = [[UIColor grayColor] CGColor];
    
    [self.commentTableView registerNib:[UINib nibWithNibName:@"VideoWindowTableViewCell" bundle:nil] forCellReuseIdentifier:TABLEVIEW_IDENTIF_VIDEO];
    [self.commentTableView registerNib:[UINib nibWithNibName:@"CommentTableViewCell" bundle:nil] forCellReuseIdentifier:TABLEVIEW_IDENTIF_COMMENT];
    [self.commentTableView registerNib:[UINib nibWithNibName:@"NewCommentsTableViewCell" bundle:nil] forCellReuseIdentifier:TABLEVIEW_IDENTIF_NEWCOMMENT];
    

}

-(void)editFn:(UIButton *)sender{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString*  mp=[userDefaults objectForKey:@"mp"];
    if(!(mp&&mp.length>5)){
        [self.view makeToast:@"请先登录" duration:1.0 position:@"center"];
        LoginViewController *vc = [LoginViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    NSDictionary *userInfo = [_dataSource objectForKey:@"userInfo"];
    NSString *mID = [userInfo objectForKey:@"uid"];
    
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString *str = [ud objectForKey:@"uid"];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:@{
                                                                                @"uid":str,
                                                                                @"target_uid":[NSString stringWithFormat:@"%@",mID],
                                                                                }];
    [NetManager POST1DataWithParams:dic withUrl:@"/index.php/AppNearby/nearbyBottomGz" header:nil success:^(id object) {
        NSLog(@"---%@",object);
        [[THud sharedInstance]showText:@"关注成功"];
        //_commentArray = [NSMutableDictionary dictionaryWithDictionary:object];
        _commentArray = [object objectForKey:@"list"];
        //[self loadData];
    } withAnimation:NO];
}

-(void)loadData{
    self.dataSource = [NSMutableDictionary dictionary];
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setObject:self.videoID forKey:@"videoId"];
    [NetManager POST1DataWithParams:dic withUrl:@"/index.php/appVideo/detailFn" header:nil success:^(id object) {
        NSLog(@"---%@",object);
        _dataSource = [NSMutableDictionary dictionaryWithDictionary:object];
        [self loadComment];
        //[self.commentTableView reloadData];
    } withAnimation:NO];
    
}

-(void)loadComment{
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setObject:self.videoID forKey:@"video_id"];
    [NetManager POST1DataWithParams:dic withUrl:@"/index.php/AppVideoComment/findVideoCommentPage" header:nil success:^(id object) {
        NSLog(@"---%@",object);
        //_commentArray = [NSMutableDictionary dictionaryWithDictionary:object];
        _commentArray = [object objectForKey:@"list"];
        [self.commentTableView reloadData];
    } withAnimation:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 2+_commentArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}


- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.row == 0 ){
        
        VideoWindowTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:TABLEVIEW_IDENTIF_VIDEO ];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.videoUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,self.dataSource[@"video_path"]]];
        NSString *nickName = [[[_dataSource objectForKey:@"userInfo"]objectForKey:@"nickname"] length] == 0?@"匿名用户":[[_dataSource objectForKey:@"userInfo"]objectForKey:@"nickname"];
        cell.label1.text = [NSString stringWithFormat:@"%@",nickName];
        cell.label2.text = [NSString stringWithFormat:@"%@",[_dataSource objectForKey:@"desc"]];
        cell.label3.text = [NSString stringWithFormat:@"%@次播放",[_dataSource objectForKey:@"play_cnt"]];
        return cell;

    }else if(indexPath.row == 1){
       CommentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:TABLEVIEW_IDENTIF_COMMENT];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [cell.shareBtn addTarget:self action:@selector(showShare) forControlEvents:UIControlEventTouchUpInside];
        [cell.likeBtn addTarget:self action:@selector(likeEvent) forControlEvents:UIControlEventTouchUpInside];
        cell.shareBlock = ^(NSString * share){
            
        };
        
        cell.label1.text = [NSString stringWithFormat:@"%@人喜欢",[_dataSource objectForKey:@"love_cnt"]];
        cell.label2.text = [NSString stringWithFormat:@"%lu热评",(unsigned long)_commentArray.count];
        
        return cell;

//    }else if (indexPath.row == 2 || indexPath.row == 4){
//        NewCommentsTableViewCell * cell1 = [tableView dequeueReusableCellWithIdentifier:TABLEVIEW_IDENTIF_NEWCOMMENT];
//        cell1.newcomment.text = @"該行要顯示的內容該行要顯示的內容該行要顯示的內容該行要顯示的內容該行要顯示的內容該行要顯示的內容該行要顯示的內容";
//        return cell1;

    } else {
        NSDictionary *dic = [_commentArray objectAtIndex:indexPath.row-2];
       NewCommentsTableViewCell * cell1 = [tableView dequeueReusableCellWithIdentifier:TABLEVIEW_IDENTIF_NEWCOMMENT];
//         * cell1 = (NewCommentsTableViewCell*)cell;
        
        cell1.newcomment.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"content"]];
        
        if ((![[dic objectForKey:@"avatar"] isEqual:[NSNull null]])&&[[dic objectForKey:@"avatar"] rangeOfString:@"http"].location != NSNotFound) {
            [cell1.avatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[dic objectForKey:@"avatar"]]] forState:UIControlStateNormal placeholderImage:[UIImage new]];
        }else{
            [cell1.avatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,[dic objectForKey:@"avatar"]]] forState:UIControlStateNormal placeholderImage:[UIImage new]];
        }
            
//        [cell1.avatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,[dic objectForKey:@"avatar"]]] forState:UIControlStateNormal placeholderImage:[UIImage new]];
        //[cell1.avatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,[dic objectForKey:@"avatar"]]] placeholderImage:[UIImage new]];
        cell1.lastTime.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"add_time"]];
        cell1.selectionStyle = UITableViewCellSelectionStyleNone;
        cell1.name.text = [dic objectForKey:@"nickname"];
        return cell1;

    }
}

-(void)likeEvent{
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString *str = [ud objectForKey:@"uid"];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:@{
                                                                               @"uid":str,
                                                                               @"video_id":self.videoID,
                                                                               }];
    [NetManager POST1DataWithParams:dic withUrl:@"/index.php/AppAttentionVideo/saveLoveVideoFn" header:nil success:^(id object) {
        NSLog(@"---%@",object);
        //_commentArray = [NSMutableDictionary dictionaryWithDictionary:object];
        _commentArray = [object objectForKey:@"list"];
        [self loadData];
    } withAnimation:NO];
}

- (void)showShare
{
    if (!_backView) {
        _backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
        _backView.backgroundColor = [UIColor blackColor];
        _backView.alpha = 0.5;
    }
    
    [self.view addSubview:_backView];
    _backView.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
    [_backView addGestureRecognizer:singleTap];
    
    _shareView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width, 117);
    [self.view addSubview:_shareView];
    [UIView animateWithDuration:0.3 animations:^{
        _shareView.frame = CGRectMake(0, self.view.frame.size.height - 117, self.view.frame.size.width, 117);
    }];

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 280;
    }else if(indexPath.row == 1){
        return 34;
    }else{
        NSDictionary *dic = [_commentArray objectAtIndex:indexPath.row-2];
        return [tableView fd_heightForCellWithIdentifier:TABLEVIEW_IDENTIF_NEWCOMMENT cacheByIndexPath:indexPath configuration:^(NewCommentsTableViewCell * cell) {
            cell.newcomment.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"content"]];
            cell.lastTime.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"add_time"]];
            if ((![[dic objectForKey:@"avatar"] isEqual:[NSNull null]])&& [[dic objectForKey:@"avatar"] rangeOfString:@"http"].location != NSNotFound) {
                [cell.avatar.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[dic objectForKey:@"avatar"]]] placeholderImage:[UIImage new]];
            }else{
                [cell.avatar.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,[dic objectForKey:@"avatar"]]] placeholderImage:[UIImage new]];
            }
            
//            [cell.avatar.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,[dic objectForKey:@"avatar"]]] placeholderImage:[UIImage new]];
            cell.name.text = [dic objectForKey:@"nickname"];
        }]+5;
        
        

    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void) backToPreView{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == self.textField) {
        [textField resignFirstResponder];
        [self.inputView becomeFirstResponder];
        return YES;
    }
    return YES;

}





- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    self.textField.text = self.inputTextField.text;
    [textField resignFirstResponder];
    return YES;
}


-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer
{
    __block UIView * VV = _shareView;
    [UIView animateWithDuration:0.3 animations:^{
        VV.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width, 100);
    }];
    [_backView removeFromSuperview];
}
//- (UIView*)duplicate:(UIView*)view
//{
//    NSData * tempArchive = [NSKeyedArchiver archivedDataWithRootObject:view];
//    return [NSKeyedUnarchiver unarchiveObjectWithData:tempArchive];
//}

- (void)dealloc
{
    ;
}

@end












